<template>
    <!-- 数据面板：用户数据分析 -->
    <div class="data-panel">
        <el-card class="filter-card">
            <div class="date-filter">
                <el-date-picker
                    v-model="startDate"
                    type="date"
                    placeholder="开始日期"
                    :picker-options="pickerOptions.start"
                    @change="handleDateChange"
                ></el-date-picker>
                <el-date-picker
                    v-model="endDate"
                    type="date"
                    placeholder="结束日期"
                    :picker-options="pickerOptions.end"
                    @change="handleDateChange"
                ></el-date-picker>
                <el-button @click="resetDateFilter" :loading="isLoading">
                    {{ isLoading ? '正在重置' : '重置' }}
                </el-button>
            </div>
        </el-card>

        <el-card class="table-card">
            <el-table :data="tableData" stripe>
                <el-table-column prop="type" label="类型"></el-table-column>
                <el-table-column prop="category" label="分类"></el-table-column>
                <el-table-column prop="count" label="数量"></el-table-column>
            </el-table>
            <div v-if="isLoading" class="loading-mask">
                <el-button :loading="isLoading">正在加载数据...</el-button>
            </div>
            <div v-else-if="errorMsg" class="error-message">
                <el-alert :title="errorMsg" type="error"></el-alert>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';

const startDate = ref('');
const endDate = ref('');
const isLoading = ref(false);
const errorMsg = ref('');
const tableData = ref([]);

// 日期选择器配置
const pickerOptions = {
    start: {
        shortcuts: false,
        disabledDate(time) {
            if (endDate.value) {
                return time.getTime() > new Date(endDate.value).getTime();
            }
            return false;
        }
    },
    end: {
        shortcuts: false,
        disabledDate(time) {
            if (startDate.value) {
                return time.getTime() < new Date(startDate.value).getTime();
            }
            return false;
        }
    }
};

// 格式化日期为 YYYY-MM-DD 格式
const formatDate = (dateString: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 数据请求函数
const fetchUserData = async () => {
    isLoading.value = true;
    errorMsg.value = '';

    try {
        const params: Record<string, string> = {};

        const start = formatDate(startDate.value);
        const end = formatDate(endDate.value);

        if (start && end) {
            params.startDate = start;
            params.endDate = end;
        } else if (start || end) {
            // 按照接口要求，startDate和endDate必须同时存在或同时不存在
            throw new Error('开始日期和结束日期必须同时选择或同时不选');
        }

        const response = await axios.get(
            'http://localhost:8080/pet-adopt/admin/dashboard/user-stats',
            { params }
        );

        // 直接处理表格数据
        const result = [];
        const data = response.data;

        // 性别数据
        data.gender?.forEach((item: any) => {
            result.push({
                type: '性别',
                category: item.gender,
                count: item.count
            });
        });

        // 地区数据
        data.region?.forEach((item: any) => {
            result.push({
                type: '地区',
                category: item.region,
                count: item.count
            });
        });

        // 年龄数据
        data.age?.forEach((item: any) => {
            result.push({
                type: '年龄',
                category: item.age_range,
                count: item.count
            });
        });

        tableData.value = result;
    } catch (error: any) {
        console.error('获取用户数据失败', error);
        if (error.response) {
            errorMsg.value = `请求失败: ${error.response.status} ${error.response.statusText}`;
        } else if (error.request) {
            errorMsg.value = '没有收到服务器响应';
        } else {
            errorMsg.value = `请求错误: ${error.message}`;
        }
    } finally {
        isLoading.value = false;
    }
};

// 处理日期变化
const handleDateChange = () => {
    fetchUserData();
};

// 重置日期筛选
const resetDateFilter = () => {
    startDate.value = '';
    endDate.value = '';
    fetchUserData();
};

onMounted(() => {
    fetchUserData();
});
</script>

<style scoped lang="scss">
.data-panel {
    padding: 20px;

  .filter-card {
        margin-bottom: 20px;
    }

  .date-filter {
        display: flex;
        gap: 10px;
        align-items: center;
    }

  .table-card {
        margin-bottom: 20px;
        position: relative;
    }

  .loading-mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgba(255, 255, 255, 0.7);
        z-index: 10;
    }

  .error-message {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        padding: 20px;
        z-index: 10;
    }
}
</style>